//
//  photoCollectionViewCell.swift
//  selectPhoto
//
//  Created by 孟祥群 on 2018/4/24.
//  Copyright © 2018年 孟祥群. All rights reserved.
//

import UIKit
import Photos
protocol PhotoCollectionViewCellDelegate: class {
    func eventSelectNumberChange(number: Int);
    
}
class photoCollectionViewCell: UICollectionViewCell {
    lazy var imageView : UIImageView = {
        let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: self.contentView.frame.size.width, height: self.contentView.frame.height))
        return imageView
    }()
    
    lazy var imageSelect: UIImageView = {
        let imageView = UIImageView(frame: CGRect(x:self.contentView.frame.size.width-27 , y: 3, width: 26, height: 26))
        imageView.image = UIImage.init(named: "picture_select")
        return imageView
    }()
    
    lazy var selectButton: UIButton = {
        let button = UIButton(frame: CGRect(x: self.contentView.frame.size.width-27, y: 3, width: 26, height: 26))
        button.addTarget(self, action: #selector(eventImageSelect), for: UIControl.Event.touchUpInside)
        return button
    }()
    
    weak var delegate: PhotoCollectionViewController?
    weak var eventDelegate: PhotoCollectionViewCellDelegate?
    var representedAssetIdentifier: String?
    var model : PHAsset?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.setUpUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func setUpUI() -> Void {
       self.contentView.addSubview(imageView)
       self.contentView.addSubview(imageSelect)
       self.contentView.addSubview(selectButton)
        
        self.imageView.contentMode = .scaleAspectFill
        self.imageView.clipsToBounds = true
    }
    
    func updateSelected(select:Bool){
        self.selectButton.isSelected = select
        self.imageSelect.isHidden = !select
        
        if select {
            self.selectButton.setImage(nil, for: UIControl.State.normal)
        } else {
            self.selectButton.setImage(UIImage(named: "picture_unselect"), for: UIControl.State.normal)
        }
    }
    
    @objc func eventImageSelect(sender: UIButton) {
        if sender.isSelected {
            sender.isSelected = false
            self.imageSelect.isHidden = true
            sender.setImage(UIImage(named: "picture_unselect"), for: UIControl.State.normal)
            if delegate != nil {
                if let index = PhotoImage.instance.selectedImage.firstIndex(of: self.model!) {
                    PhotoImage.instance.selectedImage.remove(at: index)
                }
                
                if self.eventDelegate != nil {
                    self.eventDelegate!.eventSelectNumberChange(number: PhotoImage.instance.selectedImage.count)
                }
            }
        } else {
            
            if delegate != nil {
                if PhotoImage.instance.selectedImage.count >= PhotoPickController.imageMaxSelectedNum - PhotoPickController.alreadySelectedImageNum {
                    self.showSelectErrorDialog() ;
                    return;
                } else {
                    PhotoImage.instance.selectedImage.append(self.model!)
                    
                    if self.eventDelegate != nil {
                        self.eventDelegate!.eventSelectNumberChange(number: PhotoImage.instance.selectedImage.count)
                    }
                }
            }
            
            sender.isSelected = true
            self.imageSelect.isHidden = false
            sender.setImage(nil, for: UIControl.State.normal)
            self.imageSelect.transform = CGAffineTransform(scaleX: 0.8, y: 0.8)
            UIView.animate(withDuration: 0.4, delay: 0, usingSpringWithDamping: 0.4, initialSpringVelocity: 6, options: [UIView.AnimationOptions.curveEaseIn], animations: { () -> Void in
                self.imageSelect.transform = CGAffineTransform(scaleX: 1.0, y: 1.0)
            }, completion: nil)
        }
    }
    
    private func showSelectErrorDialog() {
        if self.delegate != nil {
            let less = PhotoPickController.imageMaxSelectedNum - PhotoPickController.alreadySelectedImageNum
            
            let range = PhotoPickerConfig.ErrorImageMaxSelect.range(of:"#")
            var error = PhotoPickerConfig.ErrorImageMaxSelect
            error.replaceSubrange(range!, with: String(less))
            
            let alert = UIAlertController.init(title: nil, message: error, preferredStyle: UIAlertController.Style.alert)
            let confirmAction = UIAlertAction(title: PhotoPickerConfig.ButtonConfirmTitle, style: .default, handler: nil)
            alert.addAction(confirmAction)
            self.delegate?.present(alert, animated: true, completion: nil)
        }
    }
}
